import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { addTab, timeLimit } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
    Table,
    Button,
    Card,
    Col,
    Divider,
    Input,
    Row,
    Select,
    Modal,
    DatePicker,
    message,
    Tooltip,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

import Pagination from '../../components/Pagination';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;

const orderStatus = {
    1: '待送达',
    2: '已完成',
    3: '已取消'
};

interface TableListProps extends FormComponentProps {
    dispatch: Dispatch<any>;
    logisCenterUnmannedList: any;
    INITINFO: any;
    checkPerm: any;
    currentUser: any;
    location: any;
    loading: boolean;
    screen: string;
}

interface TableListState {
    fId: number;
    current: number;
    pageSize: number | undefined;
    gardenName: string | undefined;
    schoolName: string | undefined;
    shelfName: string | undefined;
    shelfType: string | undefined;
    cabinetName: string | undefined;
    formValues: any;
    orderInfo: any;
    phone: string;
    note: string;
    remark: string;
    reasonType: string;
    confirmPickupDialog: boolean;
    modifyPhoneDialog: boolean;
    modifyPhoneOcrDialog: boolean;
    problemDialog: boolean;
    backDialog: boolean;
    syncDialog: boolean;
    resendVisible: boolean;
    openCabVisible: boolean;
    cancelBackVisible: boolean;
    resendId: number;
    confirmInfo: any;
    confirmVisible: boolean;
    openCellVisible: boolean;
    openCellInfo: any;
    rowId: Number;
    readonlyTrue: boolean;
    isCancel: string;
    rotatingDegree: number;
    imgSize: number;
}

/* eslint react/no-multi-comp:0 */
@connect(
    ({
        logisCenterUnmannedList,
        common: { INITINFO, checkPerm },
        user: { currentUser },
        global: { screen },
        loading,
    }: any) => ({
        logisCenterUnmannedList,
        INITINFO,
        checkPerm,
        currentUser,
        screen,
        loading: loading.effects['logisCenterUnmannedList/fetch'],
    }),
)
class TableList extends React.Component<TableListProps, TableListState> {
    columns: any = [
        {
            title: '订单编号',
            dataIndex: 'orderId',
            width: 160,
            render: (text: any, record: any) => (
                <Tooltip title={text}>
                    <div
                        className="nameLink"
                        onClick={() => this.handleShowDelivery(record.orderId, record.orderId)}
                    >
                        {text}
                    </div>
                </Tooltip>
            ),
        },
        {
            title: '学校名称',
            dataIndex: 'schoolName',
            width: 150,
        },
        {
            title: '下单用户',
            dataIndex: 'userPhone',
            width: 100,
        },
        {
            title: '下单时间',
            dataIndex: 'createTime',
            width: 120,
        },
        {
            title: '联系人',
            dataIndex: 'contactPhone',
            width: 120,
            render: (text: string, record: any) => (
                <div>{record.contactName} {record.contactPhone}</div>
            )
        },
        {
            title: '订单状态',
            dataIndex: 'status',
            width: 100,
            render: (text: any, record: any) => {
                const showName = ['待送达', '已完成', '已取消'];
                return (<div>{showName[record.status - 1]}</div>)
            }
        },
        {
            title: '操作',
            fixed: 'right',
            dataIndex: 'orderId',
            width: 230,
            render: (orderId: any, record: any) => (
                <>
                    {
                        !!!([2, 3].includes(record.status)) ? (
                            <>
                                <span className="operLink" onClick={() => this.handleShowDelivery(orderId, record.orderId)}>
                                    查看
                                </span>
                                <Divider type="vertical" />
                                {record.vehicleStatus === 0 && <span className="operLink" onClick={() => {
                                    this.setState({ orderInfo: record, cancelBackVisible: true });
                                }}>
                                    取消订单
                                </span>}
                            </>
                        ) : (
                            <span className="operLink" onClick={() => this.handleShowDelivery(orderId, record.orderId)}>
                                详情
                            </span>
                        )
                    }
                </>
            ),
        },
    ];

    state: TableListState = {
        fId: 0,
        current: 1,
        pageSize: 10,
        gardenName: undefined,
        schoolName: undefined,
        shelfName: undefined,
        shelfType: undefined,
        cabinetName: undefined,
        formValues: {},
        orderInfo: {},
        phone: '',
        note: '',
        remark: '',
        reasonType: '0',
        confirmPickupDialog: false,
        modifyPhoneDialog: false,
        modifyPhoneOcrDialog: false,
        problemDialog: false,
        backDialog: false,
        syncDialog: false,
        resendVisible: false,
        openCabVisible: false,
        cancelBackVisible: false,
        resendId: 0,
        confirmInfo: {},
        confirmVisible: false,
        openCellVisible: false,
        openCellInfo: {},
        rowId: 0,
        readonlyTrue: true,
        isCancel: '0',
        rotatingDegree: 0,
        imgSize: 1,
    };

    timer: any = null;

    static getDerivedStateFromProps(props: any, state: any) {
        const { search } = props.location;
        const query = qs.parse(search, { ignoreQueryPrefix: true });

        const {
            current,
            pageSize,
            gardenName,
            schoolName,
            shelfName,
            shelfType,
            cabinetName,
            ...formValues
        } = query;

        const result = {
            ...state,
            formValues,
            gardenName,
            schoolName,
            shelfName,
            cabinetName,
            current: Number(current) || 1,
            pageSize: Number(pageSize) || (props.screen === 'sm' ? 100 : 10),
        };

        if (state.schoolName !== undefined) result.schoolName = state.schoolName;
        if (state.gardenName !== undefined) result.gardenName = state.gardenName;
        if (state.shelfName !== undefined) result.shelfName = state.shelfName;
        if (state.shelfType !== undefined) result.shelfType = state.shelfType;
        if (state.cabinetName !== undefined) result.cabinetName = state.cabinetName;

        return result;
    }

    componentDidMount() {
        this.setFieldsValue();

        const {
            logisCenterUnmannedList: { data },
        } = this.props;

        if (data?.content?.length) return;

        this.fetchSchoolList();

        const { gardenName, schoolName, shelfName, cabinetName } = this.state;

        if (gardenName) this.fetchGardenList({ name: gardenName });
        if (shelfName) this.fetchShelfList({ name: shelfName });
        if (cabinetName) this.fetchCabinetList({ name: cabinetName });

        this.fetchDeliveryList();

    }

    componentWillUmount() {

    }

    componentDidUpdate(prevProps: any, prevState: any) {
        const { formValues, current, pageSize } = this.state;
        if (!_.isEqual(formValues, prevState.formValues)
            || current !== prevState.current
            || pageSize !== prevState.pageSize
        ) {
            this.setFieldsValue();
            this.fetchDeliveryList();
        }
    }

    // 设置表单值
    setFieldsValue = () => {
        const {
            formValues: {
                startTime, endTime, ...others
            },
        } = this.state;

        if (startTime) {
            others.start_end_time = [moment(startTime), endTime ? moment(endTime) : ''];
        } else {
            // others.start_end_time = [moment(moment().subtract(2, 'days').format('YYYY-MM-DD')), ''];
        }


        const {
            form: { setFieldsValue },
        } = this.props;
        setFieldsValue(others);
    };

    // 获取校园小区列表
    fetchGardenList = (params: any) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'common/fetchGardenList2',
            payload: params,
        });
    };

    // 获取货架地堆列表
    fetchShelfList = (params: any) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'common/fetchShelfList',
            payload: params,
        });
    };

    // 获取柜体列表
    fetchCabinetList = (params: any) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'common/fetchCabinetList',
            payload: params,
        });
    };

    // 获取已开通无人车校园列表
    fetchSchoolList = (params: any = {}) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'logisCenterUnmannedList/fetchSchoolList',
            payload: params,
        });
    };

    // 查询操作权限
    fetchAuthCheckPerm = (oper: string) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'common/fetchAuthCheckPerm',
            payload: {
                oper,
                resource: 'logis:order_delivery',
            },
        });
    };


    // 获取数据
    fetchDeliveryList = () => {
        const {
            location: {
                query: { ...other },
            },
        } = this.props;
        const search = qs.stringify(other);

        const { dispatch } = this.props;
        dispatch({
            type: 'logisCenterUnmannedList/fetch',
            payload: {
                params: this.getQueryParams(),
                search,
            },
        });
    };

    // 获取查询参数
    getQueryParams = () => {
        const {
            formValues: { shelfId, ...values },
            current,
            pageSize,
        } = this.state;

        const params = {
            ...values,
            pageSize,
            current: current,
        };

        if (params.startTime === undefined) {
            // 暂时注释
            // params.startTime = moment().subtract(2, 'days').format('YYYY-MM-DD');
        }

        const key = shelfId && shelfId.split('|')[0];
        const type = shelfId && shelfId.split('|')[1];
        if (key && Number(key) !== 0) {
            params.storagePid = key;
            params.storageType = Number(type) === 0 ? 3 : 2;
            params.shelfType = Number(type);
        }

        if (params.cabinetId) {
            params.storagePid = params.cabinetId;
            params.storageType = 1;
            delete params.shelfType;
        }

        delete params.shelfId;
        delete params.cabinetId;

        return params;
    };

    /** 确认投递 */
    handleChangeConfirmModal = (confirmVisible: boolean, record: any = {}) => {
        const { id, orderType } = record;
        this.setState({
            confirmVisible,
            confirmInfo: { id, orderType },
        });
    };

    /**
     * 查询
     */
    handleSearch = (e: React.FormEvent) => {
        e.preventDefault();

        const {
            form: { validateFields },
            location: { query: prevQuery },
        } = this.props;

        validateFields((err, fieldsValue) => {
            if (err) return;
            const { start_end_time, expressId } = fieldsValue;

            if (start_end_time) {
                if (start_end_time[0]) {
                    fieldsValue.startTime = moment(start_end_time[0]).format('YYYY-MM-DD');
                } else {
                    fieldsValue.startTime = '';
                }

                if (start_end_time[1]) {
                    fieldsValue.endTime = moment(start_end_time[1]).format('YYYY-MM-DD');
                } else {
                    fieldsValue.endTime = '';
                }
            } else {
                fieldsValue.startTime = '';
                fieldsValue.endTime = '';
            }

            if (expressId === 0) delete fieldsValue.expressId;

            delete fieldsValue.start_end_time;

            const query = {
                current: '1',
                ...fieldsValue,
            };
            const {
                gardenName,
                shelfName,
                shelfType,
                cabinetName,
            } = this.state;

            if (gardenName) query.gardenName = gardenName;
            if (shelfName) {
                query.shelfName = shelfName;
                query.shelfType = shelfType;
                delete query.cabinetName;
            }
            if (cabinetName) {
                query.cabinetName = cabinetName;
                delete query.shelfName;
            }

            const { dispatch } = this.props;
            dispatch({
                type: 'logisCenterUnmannedList/cleanCount',
            });

            Object.keys(query).forEach((item: any) => !query[item] && delete query[item]);
            if (!_.isEqual(query, prevQuery)) {
                addTab(dispatch, {
                    name: '无人车订单管理',
                    url: `/logisCenter/unmannedCar/list?${qs.stringify(query)}`,
                    isTopMenu: true,
                });
            } else this.fetchDeliveryList();
        });
    };

    /**
     * 重置
     */
    handleFormReset = () => {
        const { form: { resetFields } } = this.props;
        resetFields();

        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '无人车订单管理',
            url: '/logisCenter/unmannedCar/list',
            isTopMenu: true,
        });
        dispatch({
            type: 'logisCenterUnmannedList/cleanCount',
        });
    };


    /**
     * 选择器失去焦点
     */
    onBlurSelect = (fieldName: string, dataName: string) => {
        const { form: { getFieldValue, setFieldsValue }, logisCenterUnmannedList: { data } } = this.props;
        const fieldValue = getFieldValue(fieldName);

        if (data[dataName].length && fieldValue) {
            if (fieldName === 'schoolId') {
                this.setState({ schoolName: data[dataName][0].name });
                // setFieldsValue({ [fieldName]: String(INITINFO[dataName][0].id) });
            }
        } else if (!fieldValue && fieldName === 'gardenId') {
            this.commonRest();
        } else if (!data[dataName].length) {
            setFieldsValue({ [fieldName]: undefined });
        }
    };

    commonRest = () => {
        this.setState({
            gardenName: '',
            shelfName: '',
            shelfType: '',
        });

        const { form: { setFieldsValue } } = this.props;
        setFieldsValue({ parcelPwd: undefined, shelfId: undefined });
    }

    /**
     * 选择无人车学校
     */
    handleChangeSchool = (value: string) => {
        const { form: { setFieldsValue } } = this.props;
        setFieldsValue({ schoolId: undefined });

        const { logisCenterUnmannedList: { data } } = this.props;
        const school = data.schoolList.find((item: any) => item.id === Number(value));
        this.setState({
            schoolName: school ? school.name : '',
        });
    };

    /**
     * 关闭确认取走弹窗
     */
    handleCloseCancel = () => {
        this.setState({
            cancelBackVisible: false,
        });
    };

    /**
     * 选择故障取走类型
     */
    handChangeIsOpen = (isCancel: string) => {
        this.setState({ isCancel });
    };

    /**
     * 确定取走
     */
    handleCancel = () => {
        const { orderInfo: { orderId }, isCancel } = this.state;
        const { dispatch } = this.props;
        dispatch({
            type: 'logisCenterUnmannedList/cancel',
            payload: {
                query: this.getQueryParams(),
                params: { orderId: orderId, reason: +isCancel },
            },
        });

        this.handleCloseCancel();
    };

    /**
     * 查看快递
     */
    handleShowDelivery = (id: number, expCode: string) => {
        const { dispatch } = this.props;
        addTab(dispatch, {
            name: `查看${expCode}`,
            url: `/logisCenter/unmannedCar/list/detail/${id}`,
        });
    };

    /**
     * 查看总数
     */
    handleShowCount = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'logisCenterUnmannedList/count',
            payload: this.getQueryParams(),
        });
    };

    // 分页
    onSelectChange = (type: string) => {
        const { formValues, current, pageSize } = this.state;
        const { logisCenterUnmannedList: { data } } = this.props;

        const query = {
            ...formValues,
            current: type === 'prev' ? current - 1 : current + 1,
            pageSize: pageSize,
        };

        // const contentObj = data.content.find((item: any) => item.current === current);
        // if (type === 'prev') {
        //     if (contentObj?.list?.length) {
        //         query.minId = contentObj.list[0].id;
        //     } else {
        //         const prevContentObj = data.content.find((item: any) => item.current === current - 1);
        //         const list = prevContentObj ? prevContentObj.list : [];
        //         query.preId = list[list.length - 1].id;
        //     }
        //     delete query.maxId;
        // } else if (type === 'next') {
        //     const list = contentObj ? contentObj.list : [];
        //     query.maxId = list[list.length - 1].id;
        //     delete query.minId;
        //     delete query.preId;
        // }
        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '无人车订单管理',
            url: `/logisCenter/unmannedCar/list?${qs.stringify(query)}`,
            isTopMenu: true,
        });
    };

    // 选择显示行数
    onShowSizeChange = (pageSize: number) => {
        const { formValues } = this.state;
        const query = {
            ...formValues,
            current: 1,
            pageSize: pageSize,
        };

        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '无人车订单管理',
            url: `/logisCenter/unmannedCar/list?${qs.stringify(query)}`,
            isTopMenu: true,
        });
    };

    onClickRow = ({ orderId }: any) => ({
        onClick: () => {
            this.setState({ rowId: orderId });
        },
    })

    // 渲染查询表单
    renderSearchFormElem = () => {
        const {
            form: { getFieldDecorator, getFieldValue },
            logisCenterUnmannedList: { data }
        } = this.props;

        const schoolList = data.schoolList;

        return (
            <Form onSubmit={this.handleSearch} className="tableListForm">
                <Row gutter={12}>
                    <Col md={12} sm={24}>
                        <FormItem label="　起止时间" colon={false}>
                            {getFieldDecorator('start_end_time', {
                                // initialValue: [moment(moment().subtract(2, 'days').format('YYYY-MM-DD')), ''],
                                initialValue: ['', ''],
                            })(
                                <RangePicker
                                    placeholder={['开始时间', '截止时间']}
                                    style={{ width: '100%' }}
                                    format="YYYY/MM/DD"
                                    disabledDate={current => timeLimit(current, 3)}
                                    ranges={{
                                        今天: [moment().startOf('day'), moment().endOf('day')],
                                        本周: [moment().startOf('week'), moment().endOf('week')],
                                        本月: [moment().startOf('month'), moment().endOf('month')],
                                        上月: [
                                            moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                                            moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                                        ],
                                    }}
                                />,
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="　订单编号" colon={false}>
                            {getFieldDecorator('orderId')(
                                <Input
                                    allowClear
                                    placeholder="请输入"
                                    style={{ width: '100%' }}
                                />,
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="　订单状态" colon={false}>
                            {getFieldDecorator('status')(
                                <Select allowClear placeholder="请选择">
                                    {Object.keys(orderStatus).map(key => (
                                        <Option
                                            key={String(key)}
                                            value={String(key)}
                                        >
                                            {orderStatus[key]}
                                        </Option>
                                    ))}
                                </Select>,
                            )}
                        </FormItem>
                    </Col>
                </Row>


                <Row gutter={12}>
                    <Col md={6} sm={24}>
                        <FormItem label="　学校名称" colon={false}>
                            {getFieldDecorator('schoolId')(
                                <Select
                                    showSearch
                                    allowClear
                                    placeholder="请选择"
                                    filterOption={(input, option) =>
                                        (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                                    }
                                    notFoundContent={null}
                                    // onBlur={() => this.onBlurSelect('schoolId', 'cabinetList')}
                                    onChange={this.handleChangeSchool}
                                >
                                    {schoolList.map((item: any) => (
                                        <Option
                                            key={item.id}
                                            value={String(item.id)}
                                        >
                                            {item.name}
                                        </Option>
                                    ))}
                                </Select>,
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="　下单用户" colon={false}>
                            {getFieldDecorator('userPhone')(
                                <Input
                                    allowClear
                                    placeholder="请输入手机号"
                                    style={{ width: '100%' }}
                                />,
                            )}
                        </FormItem>
                    </Col>
                </Row>
                <Row gutter={12}>
                    <Col md={24} sm={24}>
                        <div className="flexFeView" style={{ margin: '0 0 20px 0' }}>
                            <Button
                                type="primary"
                                htmlType="submit"
                                className="smallButton"
                            >
                                查询
                            </Button>
                            <Button
                                type="primary"
                                className="addButton marginL16 smallButton"
                                onClick={this.handleFormReset}
                            >
                                重置
                            </Button>
                        </div>
                    </Col>
                </Row>
            </Form>
        );
    };

    render() {
        const {
            current,
            pageSize,
            cancelBackVisible,
        } = this.state;

        const {
            loading,
            screen,
            logisCenterUnmannedList: { data },
        } = this.props;

        const contentObj = data.content.find((item: any) => item.current === current);
        const list = (contentObj ? contentObj.list : []) || [];

        if (screen === 'sm' || screen === 'lg') {
            delete this.columns[this.columns.length - 1].fixed;
        } else if (screen === 'md') {
            this.columns[this.columns.length - 1].fixed = 'right';
        }

        return (
            <>
                <PageHeader />
                <Card bordered={false} className="searchForm">
                    {this.renderSearchFormElem()}
                </Card>

                <Card bordered={false} className="tableList">
                    <Table
                        rowKey="orderId"
                        tableLayout="fixed"
                        className="statementTable tableHeight60"
                        columns={this.columns}
                        dataSource={list}
                        pagination={false}
                        loading={loading}
                        scroll={{ x: 1400 }}
                        onRow={this.onClickRow}
                    />
                    {(current > 1 || list.length > 0) && (
                        <Pagination
                            current={current}
                            pageSize={pageSize}
                            total={data.count}
                            length={list.length}
                            showCount={this.handleShowCount}
                            onChange={this.onSelectChange}
                            onShowSizeChange={this.onShowSizeChange}
                        />
                    )}
                </Card>
                <Modal
                    title="取走原因"
                    visible={cancelBackVisible}
                    maskClosable={true}
                    onOk={this.handleCancel}
                    onCancel={this.handleCloseCancel}
                >
                    <Form className="tableListForm">
                        <Row>
                            <Col md={20} sm={20}>
                                <Form.Item label="取消原因: " colon={false}>
                                    <Select
                                        onChange={this.handChangeIsOpen}
                                    >
                                        <Option key={1} value="1">同学代取</Option>
                                        <Option key={2} value="2">路过自取</Option>
                                        <Option key={3} value="3">下错订单</Option>
                                    </Select>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Modal>
            </>
        );
    }
}

export default Form.create<TableListProps>()(TableList);
